package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cake.dao.ShoppingCarDao;
import cake.dao.impl.ShoppingCarDaoImpl;
import cake.entity.ShoppingCar;
import cake.entity.User;

@WebServlet("/cartadd")
public class CartAddServlet extends HttpServlet {

	private ShoppingCarDao sc = new ShoppingCarDaoImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = (User) req.getSession().getAttribute("LoginUser");
		if (user == null) {
			resp.sendRedirect("login.html");
			return;
		}
		if (req.getParameter("kid") != null) {
			int kid = Integer.parseInt(req.getParameter("kid"));
			ShoppingCar s = sc.getShoppingCarByCid(kid, user.getId());
			if (s == null) {
				s = new ShoppingCar(0, kid, 1, user.getId());
				sc.addShopingCar(s);
			}else {
				sc.updateShoppingCar(s.getCount() + 1, kid, user.getId());
			}
		}
		resp.sendRedirect("cart.html");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		User user = (User) req.getSession().getAttribute("LoginUser");
		if (user == null) {
			resp.sendRedirect("login.html");
			return;
		}
		if (req.getParameter("kid") != null && req.getParameter("number") != null ) {
			
			int kid = Integer.parseInt(req.getParameter("kid"));
			int count = Integer.parseInt(req.getParameter("number"));
			ShoppingCar s = sc.getShoppingCarByCid(kid, user.getId());
			if(s==null) {
				s = new ShoppingCar(0, kid, count, user.getId());
				sc.addShopingCar(s);
			}else {
				sc.updateShoppingCar(s.getCount() + count, kid, user.getId());
			}
		}
		resp.sendRedirect("cart.html");
	}
}
